package cn.edu.yzu.scholarship.validator;

import cn.edu.yzu.scholarship.kit.Sak;

import com.jfinal.core.Controller;
import com.jfinal.ext.plugin.sqlinxml.SqlKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.validate.Validator;

public class ScholarActValidator extends Validator {

	@Override
	protected void validate(Controller c) {
		this.validateRegex("action", "add|del|edit", "errorInfo", "处理命令不正确！");
		
		if("del".equals(c.getPara("action"))) {
			this.validateRequired("scholarId", "errorInfo", "奖学金ID不存在！");
			return;
		}
		
		this.validateRequired("name", "errorInfo", "奖学金名称不能为空！");
		this.validateInteger("level", 1, 9, "errorInfo", "奖学金档次不正确！");
		try {
			int level = c.getParaToInt("level", 0);
			for(int i = 1 ; i <= level; i++) {
				this.validateRequired("name" + i, "errorInfo", "第" + i + "档名称不能为空！");
				this.validateLong("money" + i, "errorInfo", "第" + i + "档金额不正确！");
			}
		} catch(Exception e) {}
		
		if(Db.findFirst(SqlKit.sql("scholarship.checkMainByName"), c.getPara("scholarId"), c.getPara("name")) != null) {
			this.addError("errorInfo", "该奖学金名称已经存在！");
		}
	}

	@Override
	protected void handleError(Controller c) {
		c.renderText(Sak.toJsonStr("errorInfo",c.getAttr("errorInfo")));
	}
}
